package com.cq.digitalemployee.shiro.token.service.impl;

import com.cq.digitalemployee.shiro.token.TokenEntity;
import com.cq.digitalemployee.user.dao.SysPermissionDao;
import com.cq.digitalemployee.user.dao.SysRoleDao;
import com.cq.digitalemployee.user.dao.SysUserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Component
public class TokenServiceImpl implements com.cq.digitalemployee.shiro.token.service.TokenService {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    SysUserDao sysUserDao;

    @Autowired
    SysRoleDao sysRoleDao;

    @Autowired
    SysPermissionDao syspermissionDao;

    private String prefix = "digitalemployee:token:";

    /**
     * token过期时间：默认30分钟
     */
    private int expire = 30;

    /**
     * token过期时间单位：默认分钟
     */
    private TimeUnit timeUnit = TimeUnit.MINUTES;

    /**
     * 一次行token
     */
    private boolean onceVisit = false;

    @Override
    public TokenEntity createToken(String userId) {
        String token = UUID.randomUUID().toString();
        String key = prefix + token;

        TokenEntity tokenEntity = getToken(key);
        if (tokenEntity == null) {
            tokenEntity = new TokenEntity();
            tokenEntity.setToken(token);
            tokenEntity.setUserId(userId);
            tokenEntity.setUser(sysUserDao.selectByPrimaryKey(userId));
            tokenEntity.setRoles(sysRoleDao.findByUser(userId));
            tokenEntity.setPermissions(syspermissionDao.selectAllUserPermisson(userId));
            redisTemplate.opsForValue().set(key, tokenEntity, expire, timeUnit);
        } else {
            redisTemplate.expire(key, expire, timeUnit);
        }
        return tokenEntity;
    }

    @Override
    public TokenEntity getToken(String token) {
        String key = prefix + token;
        TokenEntity tokenEntity = (TokenEntity) redisTemplate.opsForValue().get(key);
        return tokenEntity;
    }

    @Override
    public TokenEntity getToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        return getToken(token);
    }

    @Override
    public void getTokenByUser(String userId) {

    }
}